<?php
require_once 'Artdepot/Controller/Action.php';

class ArtworkController extends Artdepot_Controller_Action
{

    public function init()
    {
		parent::init();
    }

    public function indexAction()
    {
	    $adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
    	$cateId = intval($this->_getParam('catId', 0));
		$categoryId = intval($this->_getParam('category', 0));
		$currency = strtoupper($this->_getParam('currency', 'USD'));
		$artist = intval($this->_getParam('artist', 0));
		$keyword = $this->_getParam('keyword', '');
		$page = intval($this->_getParam('page', 1));
    	if (!in_array($currency, array('EUR', 'USD', 'RMB'))) {
			$currency = 'USD';
		}
		if (strlen($keyword)>30) {
			$keyword = '';
		}
		
		if (empty($page)) {
			$page = 1;
		}
		
		$artworkTable = new Model_DbTable_ArtWork();
		$cateTable = new Model_DbTable_ArtworkCategory();
		$cates = $cateTable->fetchAll();
		$categories = array();
		$categoriesMap = array();
		$subIds = array();
		foreach ($cates as $cate) {
			if ($cate['parent']==0) {
				$categories[$cate['id']]['self'] = $cate; 
			} else {
				$categoriesMap[$cate['id']] = $cate->name;
				$categories[$cate['parent']]['childs'][] = $cate;
				if ($cateId && $cate['parent']==$cateId) {
					$subIds[] = $cate->id;
				}
			}
		}
		$subIds = implode(',', $subIds);
		$parentCategoryId = 0;
		$currentCategory = $cateTable->find($categoryId)->current();
		
		$where = '1';
		if ($categoryId) {
			$where .= " and category=$categoryId";
		}
		if ($cateId) {
			$where .= " and category in ({$subIds})";
		}
		
		if ($artist) {
			$where .= " and artist=$artist";
		}
		
		if ($keyword) {
			
			$escaped = $cateTable->getDefaultAdapter()
								->quote("%$keyword%");
								
			$subjectTable = new Model_DbTable_Subject();
			$styleTable = new Model_DbTable_Styles();
			$searchStyles = $styleTable->fetchAll("name LIKE {$escaped}");
			$searchsubjects = $subjectTable->fetchAll("name LIKE {$escaped}");
			
			
			if ($artist) {
				$where .= " and (name like {$escaped}";
				if ($searchStyles->count() > 0) {
					foreach ($searchStyles as $matchedStyles){
						$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
					}
				}
					
				if ($searchsubjects->count() > 0) {
					foreach ($searchsubjects as $matchedSubject){
						$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
					}
				}
				$where .= ")";
			}else{
				/**
				 * try to fetch artist by key words
				 */
				$artistTable = new Model_DbTable_Artist();
				$searchArtists = $artistTable->fetchAll("name like $escaped");
				if ($searchArtists->count() > 0) {
					$theArtistIds = array();
					foreach ($searchArtists as $matchedArtist){
						$theArtistIds[] = $matchedArtist->id;
					}
					$artistCondition = join(",", $theArtistIds);
				}
				
				if ($artistCondition){
					$where .= " and (name like {$escaped} OR artist IN ({$artistCondition})";
					
					if ($searchStyles->count() > 0) {
						foreach ($searchStyles as $matchedStyles){
							$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
						}
					}
						
					if ($searchsubjects->count() > 0) {
						foreach ($searchsubjects as $matchedSubject){
							$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
						}
					}
					
					$where .= ")";
				}else{
					$where .= " and (name like {$escaped}";
					
					if ($searchStyles->count() > 0) {
						foreach ($searchStyles as $matchedStyles){
							$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
						}
					}
						
					if ($searchsubjects->count() > 0) {
						foreach ($searchsubjects as $matchedSubject){
							$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
						}
					}
					
					$where .= ")";
				}
				
				
			}
			
		}
		
    	
		
		$perPage = 10;
		$offset = ($page-1)*10;
		$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$totalItemsNum = $db->fetchOne("select count(*) from art_work where {$where}");
		$totalPages = ceil($totalItemsNum/$perPage);
		$artworks = $artworkTable->fetchAll($where, 'id desc', $perPage, $offset);
		$artistsTable = new Model_DbTable_Artist();
		$artistsMap = $artistsTable->getMap();
		$this->view->artists = $artistsMap; //performance;
		$this->view->categoriesMap = $categoriesMap; //performance;
		
		
		
		
		$encodedKeyword = urlencode($keyword);
		$url = "/artwork?catId={$cateId}&category={$currentCategory->id}&currency={$currency}&artist={$artist}&keyword={$encodedKeyword}&page={page}";
		$this->view->pager = self::pager($page, $perPage, $totalItemsNum, $url, 'on', '');
		
		$this->view->title = 'Works of art - ';
		$this->view->catId = $cateId;
		$this->view->page = $page;
		$this->view->artworks = $artworks;
		$this->view->keyword = $keyword;
		$this->view->currency = $currency;
		$this->view->artist = $artist;
		$this->view->categories = $categories;
		$this->view->currentCategory = $currentCategory;
		$this->view->parentCategoryId = $parentCategoryId = $currentCategory->parent;
    }

    public function showAction()
    {
		$id = $this->_getParam('id', 0);
		$artworkTable = new Model_DbTable_ArtWork();
		$artistTable = new Model_DbTable_Artist();
		$cateTable = new Model_DbTable_ArtworkCategory();
		$subjectTable = new Model_DbTable_Subject();
		$styleTable = new Model_DbTable_Styles();
		$artwork = $artworkTable->find($id)->current();
		if (!$artwork instanceof Model_Artwork) {
			$this->error('Artwork not found.');
			return;
		}
		
		
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
		
		$artist = $artistTable->find($artwork->artist)->current();
		$comparableWorks = array();
		$comparableWorks = $artworkTable->fetchAll("artist = $artwork->artist", 'RAND() desc', 4);
		$category = $cateTable->find($artwork->category)->current();
		$parentCategory = $cateTable->find($category->parent)->current();
		$this->view->title = $artwork->name . ' - ';
		$this->view->subjectMap = $subjectTable->getMap();
		$this->view->styleMap = $subjectTable->getMap();
		$this->view->category = $category;
		$this->view->parentCategory = $parentCategory;
		$this->view->artwork = $artwork;
		$this->view->artist = $artist;
		$this->view->comparableWorks = $comparableWorks;
		
		$commentTable = new Model_DbTable_ArtworkComment();
		$this->view->comments = $commentTable->fetchAll("artwork = $id");
		$commentForm = new Form_ArtworkComment();
		$commentForm->setAction("/artwork/add-comment");
		$commentForm->getElement("artwork")->setValue($id);
		if ($this->auth->getIdentity()) {
			$this->view->commentForm = $commentForm;
			$this->view->currentCustomer = $this->auth->getIdentity();
		}
		
		//record browse history here
		$recordHistoryTable = new Model_DbTable_BrowseHistory();
		$record = array("id" => 0,
						"user_id" => $this->auth->getIdentity() ? $this->auth->getIdentity()->id : 0,
						"artwork_id" => $id,
						"browse_time" => date("Y-m-d H:i:s")
		);
		$recordHistoryTable->insert($record);	
		
		if ($this->admin->getIdentity()){
			$this->view->admin = true;
		}
		
		$this->logger->debug($this->view->admin);
		
		
    }

    public function categoryAction()
    {
        // action body
    }
    
	public function deleteCommentAction(){
    	$id = (int) $this->_request->getParam("id");
    	$table = new Model_DbTable_ArtworkComment();
    	$theComment = $table->fetchRow("id = $id");
    	if ($theComment && ( $theComment->customer == $this->auth->getIdentity()->id || $this->admin->getIdentity() ) ){
    		$theComment->delete();
    	}
    	
    	$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    }
    
    public function addCommentAction(){
    	if ($this->_request->isPost() && $this->auth->getIdentity()) {
    		$form = new Form_ArtworkComment();
    		if ($form->isValid($this->_request->getPost())){
    			$table = new Model_DbTable_ArtworkComment();
    			$values = array();
    			$values["time"] = date("Y-m-d H:i:s");
    			$values["id"] = 0;
    			$values["artwork"] = $form->getValue("artwork");
    			$values["content"] = $form->getValue("content");
    			$values["customer"] = $this->auth->getIdentity()->id;
    			$table->insert($values);
    		}
    	}
    	
    	$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    }
    

}





